
import { execSync } from 'child_process';
import fs from 'fs';
import https from 'https';
// import https from 'https';

// const { execSync } = require('child_process');
// const fs = require('fs');

// 生成自签名证书
if (!fs.existsSync('key.pem') || !fs.existsSync('cert.pem')) {
    execSync('openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj "/CN=localhost"');
}

// const https = require('https');
// const url = require('url');

const options = {
    key: fs.readFileSync('key.pem'),
    cert: fs.readFileSync('cert.pem'),
    minVersion: 'TLSv1.2'
};

const server = https.createServer(options, async (req, res) => {
    let chunks = [];
    req.on('data', chunk => {
        console.log(chunk.byteLength)
        let res = []
        for (let i = 0; i < chunk.byteLength; i++)
            res.push(chunk.readUInt8(i))
        console.log(res.toString('hex'));
        chunks.push(chunk)
    });

    await new Promise(resolve => req.on('end', resolve));
    chunks = Buffer.concat(chunks)
    const body = chunks.toString('utf8');

    // 打印完整请求信息
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
    console.log(`Headers: ${JSON.stringify(req.headers, null, 2)}`);
    console.log(`Body: ${body || '<empty>'}`);
    console.log('----------------------------------------');
    console.log(chunks.toString('hex'), chunks.toString('hex').length / 2)
    console.log('----------------------------------------');
    

    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(body);
    res.end();
    //   res.end(JSON.stringify({ received: true }));
});

server.listen(443, () => {
    console.log('HTTPS服务器运行在 https://localhost');
});

// 错误处理
server.on('clientError', (err, socket) => {
    console.error('客户端错误:', err);
    //   socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
});
